package cn.iocoder.yudao.module.trade.order.service.handler;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.api.trade.aftersale.enums.AfterSaleWayEnum;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeOrderCancelTypeEnum;
import cn.iocoder.yudao.module.trade.aftersale.service.AfterSaleService;
import cn.iocoder.yudao.module.trade.aftersale.vo.AfterSaleAgreeReqVO;
import cn.iocoder.yudao.module.trade.aftersale.vo.AppAfterSaleCreateReqVO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 已支付订单取消 {@link TradeOrderHandler} 实现类
 *
 * @author 山野羡民
 */
@Component
public class TradeOrderCancelHandler implements TradeOrderHandler {

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private AfterSaleService afterSaleService;

    @Override
    public void afterCancelOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        if (CollUtil.isEmpty(orderItems)) {
            return;
        }
        boolean needRefund = false;
        String cancelType;
        if (Objects.equals(order.getCancelType(), TradeOrderCancelTypeEnum.BUYER_CANCEL.getType())) {
            needRefund = true;
            cancelType = TradeOrderCancelTypeEnum.BUYER_CANCEL.getName();
        } else if (Objects.equals(order.getCancelType(), TradeOrderCancelTypeEnum.SELLER_CANCEL.getType())) {
            needRefund = true;
            cancelType = TradeOrderCancelTypeEnum.SELLER_CANCEL.getName();
        } else {
            cancelType = "";
        }
        if (!needRefund) {
            return;
        }
        for (TradeOrderItemDO orderItem : orderItems) {
            AppAfterSaleCreateReqVO createReqVO = new AppAfterSaleCreateReqVO();
            createReqVO.setOrderItemId(orderItem.getId());
            createReqVO.setWay(AfterSaleWayEnum.REFUND.getWay());
            createReqVO.setRefundPrice(orderItem.getPrice());
            createReqVO.setApplyReason(cancelType);
            createReqVO.setApplyDescription("");
            createReqVO.setApplyPicUrls(new ArrayList<>());
            Long afterSaleId = afterSaleService.createAfterSale(order.getUserId(), createReqVO);
            AfterSaleAgreeReqVO agreeReqVO = new AfterSaleAgreeReqVO();
            agreeReqVO.setId(afterSaleId);
            afterSaleService.agreeAfterSale(orderItem.getShopId(), agreeReqVO);
            afterSaleService.refundAfterSale(afterSaleId);
        }
    }

}
